package com.mycjj.android.util;

import static java.util.Calendar.MINUTE;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.fasterxml.jackson.databind.ObjectMapper;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.util.TypedValue;
import android.view.View;
import android.view.inputmethod.InputMethodManager;



public class Utils {

	public static String showTime(int time) {
		time /= 1000;
		int minute = time / 60;
		int hour = minute / 60;
		int second = time % 60;
		minute %= 60;
		return String.format("%s:%s", minute > 9 ? minute : "0" + minute,
				second > 9 ? second : "0" + second);
	}
	
    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

	public static boolean isExternalStorageEnable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		}
		return false;

	}

	/**
	 * 根据时间来创建文件名称
	 * 
	 * @param format
	 * @return
	 */
	public static String getFileNameByDateTime(String format) {
		return System.currentTimeMillis() + format;
	}

	/**
	 * 一天只能生成一个文件 method desc：
	 * 
	 * @param format
	 * @return
	 */
	public static String getFileNameByDay(String format) {
		SimpleDateFormat sdft = new SimpleDateFormat("yyyyMMdd");
		return sdft.format(new Date()) + format;
	}

	
	public static String generateRandomString(int length) {
		char[] init = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
				'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
				'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

		// create a char buffer of the specified length
		char[] buffer = new char[length];

		// fill each element
		for (int i = 0; i < length; i++) {
			buffer[i] = init[(int) (Math.random() * init.length)];
		}

		return new String(buffer);
	}


	public static String md5(String string) {
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(
					string.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Huh, MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Huh, UTF-8 should be supported?", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10)
				hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString();
	}

	public static String md5Low(String string) {
		byte[] hash;
		try {
			hash = MessageDigest.getInstance("MD5").digest(
					string.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("Huh, MD5 should be supported?", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Huh, UTF-8 should be supported?", e);
		}

		StringBuilder hex = new StringBuilder(hash.length * 2);
		for (byte b : hash) {
			if ((b & 0xFF) < 0x10)
				hex.append("0");
			hex.append(Integer.toHexString(b & 0xFF));
		}
		return hex.toString().toLowerCase();
	}

	private static final double EARTH_RADIUS = 6378137.0;

	public static double gps2m(double lat_a, double lng_a, double lat_b,
			double lng_b) {
		double radLat1 = (lat_a * Math.PI / 180.0);
		double radLat2 = (lat_b * Math.PI / 180.0);
		double a = radLat1 - radLat2;
		double b = (lng_a - lng_b) * Math.PI / 180.0;
		double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(radLat1) * Math.cos(radLat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	}
	
	 /**
     * hide the input method
     * 
     * @param view
     */
    public static void hideSoftInput(View view) {
        if (view == null)
            return;
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
        }
    }

    /**
     * show the input method
     * 
     * @param view
     */
    public static void showSoftInput(View view) {
        if (view == null)
            return;
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, 0);
    }
    
    /**
     * get the external storage file
     * 
     * @return the file
     */
    public static File getExternalStorageDir() {
        return Environment.getExternalStorageDirectory();
    }

    /**
     * get the external storage file path
     * 
     * @return the file path
     */
    public static String getExternalStoragePath() {
        return getExternalStorageDir().getAbsolutePath();
    }

    /**
     * get the external storage state
     * 
     * @return
     */
    public static String getExternalStorageState() {
        return Environment.getExternalStorageState();
    }


    /**
     * show a progress dialog
     * 
     * @param context
     * @param message
     * @param cancelable
     * @return return the progress dialog
     */
    public static ProgressDialog showProgressDialog(Context context,
            CharSequence message, boolean cancelable) {
        ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setCancelable(cancelable);
        progressDialog.setMessage(message);
        progressDialog.show();
        return progressDialog;
    }

    public static ProgressDialog showProgressDialog(Context context, int resId,
            boolean cancelable) {
        String text = context.getString(resId);
        return showProgressDialog(context, text, cancelable);
    }

    public static void dismissProgressDialog(Handler handler,
            final ProgressDialog dialog) {
        if (handler != null) {
            handler.post(new Runnable() {

                @Override
                public void run() {
                    dismissProgressDialog(dialog);
                }
            });
        } else {
            dismissProgressDialog(dialog);
        }
    }

    /**
     * dismiss the progress diaog
     * 
     * @param dialog
     */
    public static void dismissProgressDialog(ProgressDialog dialog) {
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }

    /**
     * judge the list is null or isempty
     * 
     * @param list
     * @return
     */
    public static boolean isEmpty(final List<? extends Object> list) {
        if (list == null || list.isEmpty()) {
            return true;
        }
        return false;
    }

    public static boolean isEmpty(final Set<? extends Object> sets) {
        if (sets == null || sets.isEmpty()) {
            return true;
        }
        return false;
    }

    public static boolean isEmpty(
            final Map<? extends Object, ? extends Object> map) {
        if (map == null || map.isEmpty()) {
            return true;
        }
        return false;
    }

    /**
     * Returns true if the string is null or 0-length.
     * 
     * @param text
     * @return
     */
    public static boolean isEmpty(final String text) {
        return TextUtils.isEmpty(text);
    }

    /**
     * return true ,if the string is numeric
     * 
     * @param str
     * @return
     */
    public static boolean isNumeric(final String str) {
        if (isEmpty(str)) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 
     * @param phone
     * @return
     */
    public static boolean matchPhone(CharSequence phone) {
        Matcher m = Patterns.PHONE.matcher(phone);
        return m.matches();
    }

    /**
     * 
     * @param email
     * @return
     */
    public static boolean matchEmail(CharSequence email) {
        Matcher m = Patterns.EMAIL_ADDRESS.matcher(email);
        return m.matches();
    }
    
    /**
     * get the width of the device screen
     * 
     * @param context
     * @return
     */
    public static int getSceenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * get the height of the device screen
     * 
     * @param context
     * @return
     */
    public static int getSceenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }
    /**
     *  get the height of the device StatusBar
     * @param context
     * @return
     */
	public static int getStatusBarHeight(Context context) {
	      int result = 0;
	      int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
	      if (resourceId > 0) {
	          result = context.getResources().getDimensionPixelSize(resourceId);
	      }
	      return result;
	}
    
    /**
     * get the density of the device
     * @param context
     * @return
     */
    public static float getSceenDensity(Context context) {
        return context.getResources().getDisplayMetrics().density;
    }

    /**
     * convert the dip value to px value
     * 
     * @param context
     * @param dipValue
     * @return
     */
    public static int dip2px(Context context, float dipValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * get the version code of the application
     * 
     * @param context
     * @return
     */
    public static int getVerCode(Context context) {
        int verCode = -1;
        try {
            verCode = context.getPackageManager().getPackageInfo(
                    getPackageName(context), 0).versionCode;
        } catch (NameNotFoundException e) {
        }
        return verCode;
    }

    /**
     * get the version name of the application
     * 
     * @param context
     * @return
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(
                    getPackageName(context), 0).versionName;
        } catch (NameNotFoundException e) {
        }
        return verName;
    }

    /**
     * get the package name of the app
     * 
     * @param context
     * @return
     */
    public static String getPackageName(Context context) {
        return context.getApplicationInfo().packageName;
    }

    /**
     * convert the string to another string which is build by the char value
     * 
     * @param str
     * @return
     */
    public static String toCharString(String str) {
        if (TextUtils.isEmpty(str)) {
            str = "null";
        }
        String strBuf = "";
        // for (int i = 0; i < str.length(); i++) {
        // int a = str.charAt(i);
        // strBuf += Integer.toHexString(a).toUpperCase();
        // }
        strBuf = String.valueOf(str.hashCode());
        return strBuf;
    }


    /**
     * query the params from the url
     * 
     * @param url
     * @param key
     * @return
     */
    public static String queryParameterValue(String url, String key) {

        if (isEmpty(key) || isEmpty(url)) {
            return "";
        }

        int indexParams = url.indexOf("?");
        if (indexParams == -1) {
            return "";
        }
        String params = url.substring(indexParams);
        System.out.println(params);

        int indexBegin = params.indexOf(key);
        if (indexBegin == -1) {
            return "";
        }
        indexBegin += key.length() + 1;
        ;
        int indexEnd = params.indexOf("&", indexBegin);
        if (indexEnd == -1) {
            return params.substring(indexBegin);
        } else {
            return params.substring(indexBegin, indexEnd);
        }
    }

    public static Map<String, String> getURLParamers(String url) {
        HashMap<String, String> datas = new HashMap<String, String>();
        if (url != null && url.length() > 0) {
            url = URLDecoder.decode(url);
            int begin = url.indexOf("?");
            if (begin != -1 && begin != (url.length() - 1)) {
                String params = url.substring(begin + 1, url.length());
                // System.out.println(params);
                String[] ps = params.split("&");
                if (ps.length > 1) {
                    for (int i = 0; i < ps.length; i++) {
                        String p = ps[i];
                        System.out.println(p);
                        int index = p.indexOf("=");
                        String key = p.substring(0, index);
                        String value = p.substring(index + 1, p.length());
                        datas.put(key, value);
                    }
                } else {
                    System.out.println("__");
                    System.out.println(ps[0]);
                    String p = ps[0];
                    int index = p.indexOf("=");
                    String key = p.substring(0, index);
                    String value = p.substring(index + 1, p.length());
                    datas.put(key, value);
                }
            }
        }
        return datas;
    }

    public static String queryHeaderValue(String headerValue, String key) {

        if (isEmpty(key) || isEmpty(headerValue)) {
            return "";
        }

        int indexBegin = headerValue.indexOf(key);
        if (indexBegin == -1) {
            return "";
        }
        indexBegin += key.length() + 1;
        int indexEnd = headerValue.indexOf(",", indexBegin);
        String value = null;
        if (indexEnd == -1) {
            value = headerValue.substring(indexBegin);
        } else {
            value = headerValue.substring(indexBegin, indexEnd);
        }
        return value.replace("'", "");
    }

    public static int getSystemVersionCode() {
        return android.os.Build.VERSION.SDK_INT;
    }

    /**
     * 
     * @param path
     * @return
     */
    public static String getFileContent(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            StringBuilder sb = new StringBuilder();
            byte buffer[] = new byte[2048];
            int len = 0;
            while ((len = fis.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, len));
            }
            return sb.toString();
        } catch (Exception e) {
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }

    /**
     * 
     * @param content
     * @param path
     * @param isReplace
     *            true:replace the file.false, append
     * @return
     */
    public static boolean saveFile(String content, String path, boolean append) {
        if (isExternalStorageEnable()) {
            // 看看本地有没有
            File cacheFile = new File(path);
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(cacheFile, append);
                fos.write(content.getBytes());
                fos.flush();
                return true;
            } catch (IOException e) {
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
        return false;
    }

    public static void printBundle(Bundle bundle) {
        Iterator<String> iterator = bundle.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            Log.e("mark","Key:" + key + "#value:" + bundle.get(key).toString());
        }
    }

    /**
     * check the sim card , if no sim card , will return false .<br>
     * other wise return true;
     * 
     * @param context
     * @return
     */
    public static boolean hasSimcard(Context context) {
        TelephonyManager manager = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        int state = manager.getSimState();
        if (state == TelephonyManager.SIM_STATE_ABSENT) {
            return false;
        }
        return true;
    }
    

    public static boolean isCharatorBegin(String headerStr) {
        if(TextUtils.isEmpty(headerStr)) {
            return false;
        }
        String header = headerStr.substring(0, 1);
        // 正则表达式，判断首字母是否是英文字母  
        Pattern pattern = Pattern.compile("^[A-Za-z]+$");  
        if (pattern.matcher(header).matches()) {
            return true;
        } else {
            return false;
        }
    }
    public static String getChractorBegin(String headerStr) {
        if(TextUtils.isEmpty(headerStr)) {
            return "#";
        }
        String header = headerStr.substring(0, 1);
        // 正则表达式，判断首字母是否是英文字母  
        Pattern pattern = Pattern.compile("^[A-Za-z]+$");  
        if (pattern.matcher(header).matches()) {
            return header;
        } else {
            return "#";
        }
    }

    
    public static String getFormateDate(Date date,String formate){
    	SimpleDateFormat sdft = new SimpleDateFormat(formate);
    	return sdft.format(date);
    }
    
    public static Date getParseDate(String date,String formate){
    	SimpleDateFormat sdft = new SimpleDateFormat(formate);
    	try {
			return sdft.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    public static String getSmsCodeFromMsg(String msg){
		StringBuffer codeBuffer = new StringBuffer("");
		if(!TextUtils.isEmpty(msg)){
	        for(int i=0;i<msg.length();i++){
	            if(msg.charAt(i) >= 48 && msg.charAt(i) <= 57){
	            	codeBuffer.append(msg.charAt(i));
	            }
	        }
	    }
		return codeBuffer.toString();
	}
    
    public static int dpToPx(Resources res, int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, res.getDisplayMetrics());
	}
    
    public static String pad(int c) {
        if (c >= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }
    
	
	public static String getMonth(int month){
		return month < 10 ? "0"+month : String.valueOf(month);
	}

	public static boolean isYearEquals(Calendar mFirstDateOfMonthCal,
			Calendar mLastDateOfMonthCal,Calendar mCurrentDateCal) {
		return mFirstDateOfMonthCal.get(Calendar.YEAR) == mCurrentDateCal
				.get(Calendar.YEAR);
	}

	public static boolean isMonthEquals(Calendar mFirstDateOfMonthCal,
			Calendar mLastDateOfMonthCal,Calendar mCurrentDateCal) {
		boolean isYear = isYearEquals(mFirstDateOfMonthCal, mLastDateOfMonthCal,mCurrentDateCal);
		boolean isMonth = mFirstDateOfMonthCal.get(Calendar.MONTH) == mCurrentDateCal
				.get(Calendar.MONTH);
		return isYear && isMonth;
	}

	public static Calendar lastDayOfMonth(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int value = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		cal.set(Calendar.DAY_OF_MONTH, value);
		cal.set(Calendar.HOUR_OF_DAY, 12);
		cal.add(MINUTE, 1);
		return cal;
	}
	
	public static String MapToJsonStr(Map<String,Object> map){
		String strJson = "";
		ObjectMapper mapper = new ObjectMapper();
//		Map<String,Object> dataMap = new HashMap<String, Object>();
//		dataMap.put("data", map);
		try {
			strJson = mapper.writeValueAsString(map);
			
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		return strJson;
	}

}
